import { resourceServiceClient} from "./grpcweb_auth";
import { Empty } from "@/types/proto/google/protobuf/empty";
import { GetResourceRequest, GetResourceBinaryRequest, DeleteResourceRequest} from "@/types/proto/api/v1/resource_service";
import { CreateResourceRequest, Resource,ListResourcesRequest,ListResourcesResponse} from "@/types/proto/api/v1/resource_service";
import { HttpBody } from "@/types/proto/google/api/httpbody";

export async function CreateResource(data: CreateResourceRequest): Promise<Resource> {
    try {
      return resourceServiceClient.createResource(data)
    } catch (error) {
      console.error('gRPC request failed:', error);
      throw error;
    }
}

export async function ListResources(data: ListResourcesRequest): Promise<ListResourcesResponse> {
    try {
      return resourceServiceClient.listResources(data)
    } catch (error) {
      console.error('gRPC request failed:', error);
      throw error;
    }
}

export async function GetResource(data: GetResourceRequest): Promise<Resource> {
  try {
    return resourceServiceClient.getResource(data)
  } catch (error) {
    console.error('gRPC request failed:', error);
    throw error;
  }
}

export async function GetResourceBinary(data: GetResourceBinaryRequest): Promise<HttpBody> {
  try {
    return resourceServiceClient.getResourceBinary(data)
  } catch (error) {
    console.error('gRPC request failed:', error);
    throw error;
  }
}

export async function DeleteResource(data: DeleteResourceRequest): Promise<Empty>  {
  try {
    return resourceServiceClient.deleteResource(data)
  } catch (error) {
    console.error('gRPC request failed:', error);
    throw error;
  }
}

export const GetResourceUrl = (resource: Resource) => {
  if (resource.externalLink) {
    return resource.externalLink;
  }

  return `${window.location.origin}/file/${resource.urn}/${resource.filename}`;
};